package main

import (
	"flag"
	"net/http"
	"runtime/trace"
	"time"

	_ "github.com/share309/gojwt"
	"google.golang.org/grpc"
	"log"
	"net"
	_ "user_srv/basic/init"
	__ "user_srv/basic/userproto"
	"user_srv/handler/service"
)

// server is used to implement helloworld.GreeterServer.

func main() {
	flag.Parse()

	// 启动pprof和trace服务在单独的goroutine中
	go func() {
		// pprof默认已经注册到http.DefaultServeMux
		// 添加自定义的trace端点
		http.HandleFunc("/debug/trace", func(w http.ResponseWriter, r *http.Request) {
			w.Header().Set("Content-Type", "application/octet-stream")
			w.Header().Set("Content-Disposition", "attachment; filename=trace.out")
			trace.Start(w)
			defer trace.Stop()

			// 设置超时
			timer := time.AfterFunc(10*time.Second, func() {
				trace.Stop()
			})
			defer timer.Stop()

			// 等待客户端断开连接或超时
			<-r.Context().Done()
		})

		log.Println("Starting pprof server on :6061")
		if err := http.ListenAndServe(":6061", nil); err != nil {
			log.Printf("pprof server error: %v", err)
		}
	}()

	lis, err := net.Listen("tcp", "127.0.0.1:50051")
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}
	s := grpc.NewServer()
	__.RegisterUserServer(s, &service.Server{})
	log.Printf("server listening at %v", lis.Addr())
	log.Println("pprof and trace available at http://localhost:6061/debug/pprof/")
	if err := s.Serve(lis); err != nil {
		log.Fatalf("failed to serve: %v", err)
	}
}
